<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <el-tab-pane label="角色管理">
            <!-- 新增角色 -->
            <el-row style="height:60px;">
              <el-button size="small" type="primary" icon="el-icon-plus" @click="showDialog=true">新增角色</el-button>
              <el-button size="small" type="danger" icon="el-icon-delete" :disabled="multipleSelection.length===0" @click="delManay">批量删除</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list" @selection-change="handleSelectionChange">
              <el-table-column type="selection" />
              <el-table-column type="index" label="序号" />
              <el-table-column align="center" width="240px" prop="name" label="角色名称" />
              <el-table-column align="center" width="440px" prop="description" label="描述" />
              <el-table-column align="center" label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" size="small" @click="assignPerm(scope.row.id)">分配权限</el-button>
                  <el-button type="success" size="small" @click="editRow(scope.row)">编辑</el-button>
                  <el-button type="danger" size="small" @click="delRow(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <br>
            <!-- 分页器 -->
            <el-pagination
              :current-page.sync="page.page"
              :page-sizes="[2, 3, 4, 10]"
              :page-size="page.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="page.total"
              background
              @size-change="sizeChange"
              @current-change="currentChange"
            />

          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="formData.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="formData.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="formData.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="formData.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <!-- 新增/编辑的弹框 -->
    <el-dialog
      :title=" roleForm.id ? '编辑角色':'新增角色' "
      :visible.sync="showDialog"
      width="40%"
      @close="reset"
    >
      <!-- 表单内容 -->
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="80px" :inline="false" size="normal">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" rows="3" type="textarea" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button size="small" @click="showDialog = false">取消</el-button>
        <el-button size="small" type="primary" @click="btnOK">确定</el-button>
      </span>
    </el-dialog>

    <!-- 角色关联权限 -->
    <el-dialog title="角色授权" :visible.sync="showPermDialog" @close="permIds=[]">
      <el-tree
        v-if="showPermDialog"
        ref="tree"
        :data="permList"
        show-checkbox
        :props="{ label:'name' }"
        node-key="id"
        :default-checked-keys="permIds"
      />
      <span slot="footer">
        <el-button size="small" @click="showPermDialog = false">取消</el-button>
        <el-button size="small" type="primary" @click="btnPermOK">确定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  getRoleList,
  getCompanyInfo,
  addRole,
  updateRole,
  deleteRole,
  getRoleInfoById,
  assignPerm
} from '@/api/setting'
import { mapGetters } from 'vuex'
import { getPermissionList } from '@/api/permission'
import { tranListToTreeData } from '@/utils'
export default {
  name: 'Setting',
  data() {
    return {
      page: {
        page: 1, // 页码
        pagesize: 2, // 每页数量
        total: 0
      },
      list: [],
      // 公司信息
      formData: {},
      showDialog: false,
      // 表单变量
      roleForm: {
        name: '',
        description: ''
      },
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在2-8', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在2-20', trigger: 'blur' }
        ]
      },
      // 多选勾中的数据
      multipleSelection: [],
      // 角色授权弹框
      showPermDialog: false,
      // 所有的权限
      permList: [],
      // 当前角色的权限
      permIds: [],
      // 当前角色的id
      roleId: ''
    }
  },
  computed: {
    ...mapGetters(['companyId'])
  },
  created() {
    this.getRoleList()
    this.getCompanyInfo()
  },
  methods: {
    // 获取列表数据
    async getRoleList() {
      const { total, rows } = await getRoleList(this.page)
      this.page.total = total
      this.list = rows
    },

    // 获取公司信息
    async getCompanyInfo() {
      this.formData = await getCompanyInfo(this.companyId)
    },
    // 每页数量更换
    sizeChange(val) {
      this.page.pagesize = val
      this.getRoleList()
    },
    // 页码更换事件
    currentChange(val) {
      this.page.page = val
      this.getRoleList()
    },
    // 表单提交事件
    async btnOK() {
      // 1. 表单校验
      try {
        await this.$refs.roleForm.validate()
      } catch (error) {
        return console.log(error)
      }
      // 2. 数据处理
      // 3. 发送请求
      if (this.roleForm.id) {
        // 修改
        await updateRole(this.roleForm)
      } else {
        // 添加
        await addRole(this.roleForm)
      }
      // 4. 成功处理
      this.$message.success('操作成功')
      this.showDialog = false
      this.getRoleList()
    },
    // 关闭事件
    reset() {
      this.roleForm = {
        name: '',
        description: ''
      }
    },
    // 编辑事件
    editRow(val) {
      this.roleForm = { ...val }
      this.showDialog = true
    },
    // 删除事件
    async delRow(val) {
      // 确认框
      try {
        await this.$confirm('确定删除吗?')
      } catch (error) {
        return console.log(error)
      }
      // 删除请求
      await deleteRole(val.id)
      // 成功操作
      this.$message.success('删除成功')
      this.getRoleList()
    },
    // 多选操作事件
    handleSelectionChange(val) {
      // val 就是目前勾选中的数据数组！
      this.multipleSelection = val
    },
    // 批量删除操作
    async delManay() {
      // 确认框
      try {
        await this.$confirm('确定批量删除吗?')
      } catch (error) {
        return console.log(error)
      }
      // 删除请求
      const idArr = this.multipleSelection.map(val => val.id)
      // idArr 提交给后台就可以！
      console.log(idArr)
    },
    // 角色授权提交事件
    async btnPermOK() {
      const permIds = this.$refs.tree.getCheckedKeys()
      const halfPermIds = this.$refs.tree.getHalfCheckedKeys()
      if (permIds.length === 0) return this.$message.warning('请勾选权限')
      await assignPerm({
        id: this.roleId, // 角色ID
        permIds: [...permIds, ...halfPermIds] // 角色的权限
      })
      this.$message.success('更新成功')
      this.showPermDialog = false
    },
    // 角色授权打开
    async assignPerm(id) {
      // 获取所有权限
      const res = await getPermissionList()
      this.permList = tranListToTreeData(res, '0')
      // 获取当前角色的权限
      const { permIds } = await getRoleInfoById(id)
      this.permIds = permIds

      this.roleId = id
      // 打开弹框
      this.showPermDialog = true
    }
  }
}
</script>

<style>

</style>
